"""
Copyright (c) 2023 - present SKbioinfo
"""
from flask_restful import Resource
from flask import request,jsonify
from apps.API.utils.log_helper import lg
from apps.API.connector.db_common import *
from apps.API.common.common_time import *
from apps.API.common.db_table_config import *
from apps.API.common.common_generate_id import id_generator
import re

table_name = {
    "样品审核" : "sms_sample",
    "样品清退" : "sms_sample",
    "样品编辑" : "sms_sample",
    "样品领退" : "sms_sample",
}
        
class interfaceQueryHistory(Resource):
    def post(self):
        try:
            user_list=""
            for user in request.json["user_id"]:
                user_list= user_list + "\"" + user + "\","
            user_list=user_list.rstrip(",")
            ### SQL: query record history sql ###
            record_history_sql = '''
                SELECT * FROM {table_name} WHERE username IN ({user_list})
            '''.format(
                table_name=common_tables.system_log_db["name"],
                user_list=user_list
            ) 
            base_info = dic_query_info(record_history_sql)
            response = jsonify(base_info)
            response.status = 202
            return response
        except Exception as e:
            lg.error(e)
            return 400

class interfaceRecord(Resource):
    def __init__(self):
        self.gen=id_generator(name=common_tables.system_log_db["name"])
        self.mapping={
            "sample_amount":"原始样品量"
        }
    
    def get(self):
        try:
            cols = '''
                id,
                username,
                tablename,
                check_user,
                action_id,
                action_type,
                action_tag,
                operate_time,
                operate_details,
                reason_details,
                step
            '''
            ### SQL: query record infos ###
            record_infos_sql = '''
                SELECT {cols} FROM {table_name} 
            '''.format(
                cols=cols,
                table_name=common_tables.system_log_db["name"]
            )
            base_info=dic_query_info(record_infos_sql)
            response=jsonify(base_info)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
            return 404
    
    def post(self):
        cols = '''
            username,
            tablename,
            check_user,
            action_id,
            action_type,
            action_tag,
            operate_time,
            operate_details,
            reason_details,
            step
        '''
        ACT_prefix=self.gen.generate_prefix(tag="act")
        ACT_id=self.gen.generate_id(col="action_id")
        action_id=int(ACT_id["action_id"]) + 1
        if request.json["actionType"].split('|')[1] == "删除":
            content = ""
            action_type = 0
            action_tag = ""
            if re.match("^样品",request.json["actionType"].split('|')[0]):
                content = '''
                    SAMPLE {sample_id}
                '''.format(
                    sample_id = request.json["data"]["sample_id"]
                )
                if re.match("样品清退",request.json["actionType"].split('|')[0]):
                    action_type=-1
                    action_tag="清退"
                else:
                    action_type=0
                    action_tag="删除"
            values='''
                \"{username}\",
                \"{tablename}\",
                \"{check_user}\",
                \"{action_id}\",
                \"{action_type}\",
                \"{action_tag}\",
                \"{operate_time}\",
                \"{operate_details}\",
                \"{reason_details}\",
                \"{step}\"
            '''.format(
                    username=request.json["username"],
                    tablename=table_name[request.json["actionType"].split("|")[0]],
                    step=request.json["actionType"].split("|")[0],
                    check_user=request.json["username"],
                    action_id=ACT_prefix + str(action_id),
                    action_type=action_type,
                    action_tag=action_tag,
                    operate_time=get_current_time(),
                    operate_details='''{content} FROM {table_name}'''.format(
                        content=content,
                        table_name=table_name[request.json["actionType"].split("|")[0]],
                    ),
                    reason_details=request.json["reason"]
            )
            ### SQL: Delete operation record ###
            Delete_record_sql='''
                INSERT INTO {table_name} ({cols}) VALUES ({values})
            '''.format(
                table_name=common_tables.system_log_db["name"],
                cols=cols,
                values=values
            )
            add_info(Delete_record_sql)
            return 202
        if request.json["actionType"].split('|')[1] == "编辑":
            if re.match("^样品",request.json["actionType"].split('|')[0]):
                query_pervious_info = ""
                if request.json["actionType"].split('|')[0] != "样品领退":
                    check_cols='''
                        id,
                        project_id,
                        client_id,
                        sample_id,
                        sample_name,
                        lot_number,
                        size,
                        sample_amount,
                        current_amount,
                        arrive_time,
                        instock_time,
                        create_time,
                        disp_amount,
                        disp_size,
                        modify_time,
                        status
                    '''
                    ### SQL: query previous infos ###
                    query_pervious_info = '''
                        SELECT {cols}
                        FROM {table_name}
                        WHERE sample_id=\"{sample_id}\"
                    '''.format(
                        cols=check_cols,
                        table_name=common_tables.sample_db["name"],
                        sample_id=request.json["data"]["sample_id"]
                    )
                elif request.json["actionType"].split('|')[0] == "样品领退":
                    check_cols='''
                        tb1.id,
                        tb1.receipt_id,
                        tb1.service_id,
                        tb1.service_name,
                        tb1.extra_info,
                        tb1.project_id,
                        tb1.sample_id,
                        tb1.receipt_amount,
                        tb1.return_amount,
                        tb1.reason,
                        tb1.create_time,
                        tb1.modify_time,
                        tb1.applicant,
                        tb1.check_user,
                        tb1.dflag,
                        tb1.rflag,
                        tb1.rec_stat,
                        tb1.locale,
                        tb2.current_amount,
                        tb2.disp_amount,
                        tb2.disp_size,
                        tb2.instock_time,
                        tb2.lot_number,
                        tb2.sample_amount,
                        tb2.sample_name,
                        tb2.size,
                        tb2.status
                    '''
                    ### SQL: query previous infos ###
                    query_pervious_info = '''
                        SELECT {cols}
                        FROM {table_one} as tb1
                        LEFT JOIN {table_two} as tb2
                        ON tb1.sample_id = tb2.sample_id
                        WHERE tb1.sample_id=\"{sample_id}\"
                    '''.format(
                        cols=check_cols,
                        table_one=common_tables.receipt_db["name"],
                        table_two=common_tables.sample_db["name"],
                        sample_id=request.json["data"]["sample_id"]
                    )
                ### compare pervious infos ###
                previous_infos = dic_query_info(query_pervious_info)
                op_details = ""
                for info in request.json["data"]:
                    if request.json["data"][info] == previous_infos[0][info]:
                        pass
                    elif info not in ["modify_time","create_time","instock_time","arrive_time"]:
                        op_details= op_details + '''{tag}:[{previous}=>{later}]'''.format(
                            tag=info,
                            previous=previous_infos[0][info],
                            later=request.json["data"][info]
                        ) + ","
                if op_details == "":
                    op_details = "[无修改]"
                op_details=op_details.rstrip(",")
                ### SQL: ###
                values='''
                    \"{username}\",
                    \"{tablename}\",
                    \"{check_user}\",
                    \"{action_id}\",
                    \"{action_type}\",
                    \"{action_tag}\",
                    \"{operate_time}\",
                    \"{operate_details}\",
                    \"{reason_details}\",
                    \"{step}\"
                '''.format(
                    username=request.json["username"],
                    tablename=table_name[request.json["actionType"].split("|")[0]],
                    step=request.json["actionType"].split("|")[0],
                    check_user=request.json["username"],
                    action_id=ACT_prefix + str(action_id),
                    action_type=1,
                    action_tag="编辑",
                    operate_time=get_current_time(),
                    operate_details='''{content} FROM {table_name}'''.format(
                        content=op_details,
                        table_name=table_name[request.json["actionType"].split("|")[0]],
                    ),
                    reason_details=request.json["reason"]
                )
                ### SQL: 
                Edit_record_sql='''
                    INSERT INTO {table_name} ({cols}) VALUES ({values})
                '''.format(
                    table_name=common_tables.system_log_db["name"],
                    cols=cols,
                    values=values
                )
                add_info(Edit_record_sql)
                return 202